import {useEffect, useState} from 'react';
import { Input,Form,Button,Tabs,Popconfirm } from 'antd';
import styles from './index.less';
import {InternalLinkModal} from "@/pages/Dashboard/Knowledge/components/InternalLink";
import {Link} from "umi";
import { ChooseColor } from "@/components/SketchColor";
// @ts-ignore
import {getDi} from "bpmn-js/lib/util/ModelUtil";
import {CloseOutlined} from "@ant-design/icons";
const CustomPropertiesPanel = (props:any) => {
    const { modeler } = props;
    const [curElement, setCurElement] = useState(null);
    const [name, setName] = useState('');
    const [id, setId] = useState('');
    const [ remark,setRemark ] = useState("");
    const [ knowledgeName,setKnowledgeName ] = useState("");
    const [ knowledgeId,setKnowledgeId ] = useState("");
    const [ hidden,setHidden ] = useState(true);
    const [ showInternalLinkModal ,setShowInternalLinkModal ] = useState(false);
    const [ fillColor,setFillColor ] = useState({
        r: '255',
        g: '255',
        b: '255',
        a:'1',
    })

    const [ strokeColor,setStrokeColor ] = useState({
        r: '0',
        g: '0',
        b: '0',
        a:'1',
    })

    const [ fontColor,setFontColor ] = useState({
        r: '0',
        g: '0',
        b: '0',
        a:'1',
    })

    const changeFillColor = (color:any) => {
        setFillColor(color);
        // console.log(color);
        if(modeler){
            const commandStack:any = modeler.get('commandStack');
            // const modeling = modeler.get('modeling');
            if(curElement){
                // modeling.setColor([ curElement ], {
                //     fill: 'rgba(0, 80, 0, 0.4)',
                // });
                commandStack.execute('element.updateProperties', {
                    element: curElement,
                    properties: {
                        di: {
                            'background-color':`rgba(${color.rgb.r},${color.rgb.g},${color.rgb.b},${color.rgb.a})`
                        }
                    }
                });
            }

        }
    }

    const changeStorkeColor = (color:any) => {
        setStrokeColor(color);
        if(modeler){
            const commandStack:any = modeler.get('commandStack');
            // const modeling = modeler.get('modeling');
            if(curElement){
                // modeling.setColor([ curElement ], {
                //     stroke: color.hex,
                // });
                commandStack.execute('element.updateProperties', {
                    element: curElement,
                    properties: {
                        di: {
                            'border-color':`rgba(${color.rgb.r},${color.rgb.g},${color.rgb.b},${color.rgb.a})`
                        }
                    }
                });
            }

        }
    }

    const changeFontColor = (color:any) => {
        setFontColor(color);
        // console.log(color);
        if(modeler){
            const commandStack:any = modeler.get('commandStack');
            // const modeling = modeler.get('modeling');
            if(curElement){
                // modeling.setColor([ curElement ], {
                //     fill: 'rgba(0, 80, 0, 0.4)',
                // });
                commandStack.execute('element.updateModdleProperties', {
                    element: curElement,
                    moddleElement: getDi(curElement).label,
                    properties: {
                        color: `rgba(${color.rgb.r},${color.rgb.g},${color.rgb.b},${color.rgb.a})`
                    }
                });
            }

        }
    }

    const getRGB=(str:any)=>{
        if(str){
            const vals = str.substring(str.indexOf('(') +1, str.length -1).split(',');
            return {
                r: Number(vals[0]),
                g: Number(vals[1]),
                b: Number(vals[2]),
                a: Number(vals[3]),
            };
        }
        else{
            return null;
        }

    }

    useEffect(()=>{
        if (modeler) {
            modeler.on('selection.changed', (e:any) => {
                const selectElements:any = e.newSelection;
                window.addEventListener('keydown', (e:any)=>{
                    switch (e.keyCode) {
                        case 46: // 向左事件 - 位置减减
                            if(modeler){
                                const modeling = modeler.get('modeling');
                                modeling.removeElements(selectElements);
                            }
                            break;
                    }
                });
                if (e.newSelection.length == 1 && e.newSelection[0] !== curElement) {
                    setHidden(false);
                    setCurElement(e.newSelection[0]);
                    console.log(e.newSelection[0]);
                    setId(e.newSelection[0].businessObject.id);
                    setName(e.newSelection[0].businessObject.name);
                    setRemark(e.newSelection[0].businessObject.remark);
                    setKnowledgeId(e.newSelection[0].businessObject.knowledgeId);
                    setKnowledgeName(e.newSelection[0].businessObject.knowledgeName);
                    // @ts-ignore
                    setFillColor(getRGB(getDi(e.newSelection[0])['background-color'])||fillColor);
                    // @ts-ignore
                    setStrokeColor(getRGB(getDi(e.newSelection[0])['border-color'])||strokeColor);
                    // @ts-ignore
                    setFontColor(getRGB(getDi(e.newSelection[0]).label && getDi(e.newSelection[0]).label['color'])||fontColor)
                }
                else if(e.newSelection.length > 1){
                    setHidden(true);
                }
                else if(e.newSelection.length === 0){
                    // 没选中任何目标，就选中 process
                    const elementRegistry = modeler.get('elementRegistry');
                    const processEl = elementRegistry.find((el:any) => el.type === 'bpmn:Process');
                    if (processEl) {
                        setCurElement(processEl);
                        setId(processEl.businessObject.id);
                        setName(processEl.businessObject.name);
                        setRemark(processEl.businessObject.remark);
                        // setKnowledgeId(processEl.businessObject.knowledgeId);
                        // setKnowledgeName(processEl.businessObject.knowledgeName);
                        setHidden(true);
                    }
                }
            });
        }
    },[modeler])

    const updateProperties = (o:any) => {
        if(modeler){
            const modeling = modeler.get('modeling');
            modeling.updateProperties(curElement, o);
        }
    }

    //设置好插入内部链接后，点击确定按钮是触发
    //todo: onSuccessInsert
    const onSuccessInsert=(item:any)=>{
        setShowInternalLinkModal(false);
        setKnowledgeName(item.title);
        setKnowledgeId(item.id);
        updateProperties({
            knowledgeId:item.id,
            knowledgeName:item.title,
        })
    }

    return(
        <div className={styles.wapper}>
            <div style={{fontSize:14,fontWeight:"bold"}}>{id}</div>
            <div style={{color:"#c1c1c1"}}>[{curElement && curElement.type}]</div>

            <Tabs defaultActiveKey="1">
                <Tabs.TabPane tab={`常规`} key={`1`}>
                    <Form.Item label={`节点名称`} hidden={hidden}>
                        <Input
                            value={name}

                            onChange={(event) => {
                                setName(event.target.value);
                                updateProperties({ name: event.target.value });
                            }}/>
                    </Form.Item>
                    <Form.Item label={`描述(限50字)`} hidden={hidden}>
                        <Input.TextArea
                            rows={4}
                            maxLength={50}
                            value={remark}
                            onChange={(event) => {
                                setRemark(event.target.value);
                                updateProperties({ remark: event.target.value});
                            }}/>
                    </Form.Item>
                    <Form.Item label={`关联知识`} hidden={hidden}>
                        <Button type="primary" block onClick={()=>setShowInternalLinkModal(true)}>选择知识</Button>
                        {
                            knowledgeId &&
                            <div className={styles.knowledgeContainer}>
                                <div className={styles.knowledgeContent} >
                                    <Link title={knowledgeName} target="_blank" to={`/knowledge/details/${knowledgeId}`}>{knowledgeName}</Link>
                                </div>
                                <Popconfirm
                                    title="您确定要删除该知识的关联吗？"
                                    onConfirm={()=>{
                                        setKnowledgeId("");
                                        setKnowledgeName("");
                                        updateProperties({
                                            knowledgeId:"",
                                            knowledgeName:"",
                                        })
                                    }}
                                    okText="是"
                                    cancelText="否"
                                >
                                    <Button
                                        type="link"
                                        size="small"
                                        danger
                                        icon={<CloseOutlined />}
                                    ></Button>
                                </Popconfirm>

                            </div>

                        }
                    </Form.Item>
                </Tabs.TabPane>
                <Tabs.TabPane tab={`样式`} key={`2`}>
                    <Form.Item label={`填充颜色`} hidden={hidden}>
                        <ChooseColor toolColor={fillColor} setTooloColor={changeFillColor}></ChooseColor>
                    </Form.Item>
                    <Form.Item label={`边框颜色`} hidden={hidden}>
                        <ChooseColor toolColor={strokeColor} setTooloColor={changeStorkeColor}></ChooseColor>
                    </Form.Item>
                    <Form.Item label={`字体颜色`} hidden={hidden}>
                        <ChooseColor toolColor={fontColor} setTooloColor={changeFontColor}></ChooseColor>
                    </Form.Item>
                </Tabs.TabPane>
            </Tabs>

            {showInternalLinkModal && (
                <InternalLinkModal
                    show={showInternalLinkModal}
                    onSelect={(item: any) => {
                        onSuccessInsert(item);
                    }}
                    onCancel={() => setShowInternalLinkModal(false)}
                ></InternalLinkModal>
            )}
        </div>
    )
}

export default CustomPropertiesPanel;